package com.hermes.biz.search.conn;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;

public class SQLConnection extends SqlMapClientDaoSupport{
	Connection conn = null;
	String url = "jdbc:mysql://localhost:3306/";  
    String dbName = "hermes";  
    String driverName = "com.mysql.jdbc.Driver";  
    String userName = "root";  
    String password = "admin";
	public Connection getConnction() throws InstantiationException, IllegalAccessException, ClassNotFoundException{
		  
	    Connection con=null;  
	    
		try {
			 String filePath = getFilePath();
			 readFileByLines(filePath);
			 Class.forName(driverName).newInstance();
			 
			 conn=DriverManager.getConnection(url, userName,password);
		} catch (SQLException e) {		
			e.printStackTrace();
		}				
		return conn;
	}	
	public String getFilePath(){
		 URL pth = Thread.currentThread().getContextClassLoader().getResource("");		
		 String pthstr = pth.toString();
		 pthstr= pthstr+"WEB-INF/classes/conf/database/database.properties";
		 pthstr = pthstr.substring(6);
		 return pthstr;
	}
	  public  void readFileByLines(String fileName) {
	        File file = new File(fileName);
	        BufferedReader reader = null;
	        try {
	            System.out.println("");
	            reader = new BufferedReader(new FileReader(file));
	            String tempString = null;
	            int line = 1;
	            // 涓�璇诲叆涓�锛岀洿鍒拌鍏ull涓烘枃浠剁粨鏉�
	            while ((tempString = reader.readLine()) != null) {
	               if(tempString.startsWith("driver=")){
	                	driverName = tempString.substring(7);
	                }
	                if(tempString.startsWith("url=")){
	                	url = tempString.substring(4);
	                }
	                if(tempString.startsWith("username=")){
	                	userName = tempString.substring(9);
	                }
	                if(tempString.startsWith("password=")){
	                	password = tempString.substring(9);
	                } 
	                line++;
	            }
	            reader.close();
	        } catch (IOException e) {
	            e.printStackTrace();
	        } finally {
	            if (reader != null) {
	                try {
	                    reader.close();
	                } catch (IOException e1) {
	                }
	            }
	        }
	    }
}
